package com.doge.walknovel.core.account

import android.app.Activity
import android.content.Intent
import com.doge.walknovel.analysis.analysisEvent
import com.doge.walknovel.analysis.login_facebook
import com.doge.walknovel.utils.isMainThread
import com.doge.walknovel.utils.log
import com.facebook.CallbackManager
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.GraphRequest
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult

object FacebookLoginHelper {
    private val callbackManager by lazy { CallbackManager.Factory.create() }

    interface Callback {
        fun onResult(isSuccess: Boolean, data: FacebookUser?, error: String?)
    }

    private val listeners = mutableListOf<Callback>()

    fun registerCallback(callback: Callback) {
        if (!listeners.contains(callback)) listeners.add(callback)
    }

    fun unregisterCallback(callback: Callback) {
        if (listeners.contains(callback)) listeners.remove(callback)
    }

    fun login(activity: Activity) {
        require(isMainThread())
        analysisEvent(login_facebook)

        LoginManager.getInstance().logInWithReadPermissions(activity, listOf("public_profile"))
        LoginManager.getInstance().registerCallback(
            callbackManager,
            object : FacebookCallback<LoginResult> {
                override fun onSuccess(result: LoginResult?) {
                    GraphRequest.newMeRequest(result?.accessToken) { json, resp ->
                        log("facebook user json $json resp $resp token ${result?.accessToken}")
                        val user = FacebookUser.from(json, result?.accessToken)
                        listeners.forEach { it.onResult(true, user, null) }
                    }?.executeAsync()
                }

                override fun onCancel() {
                    listeners.forEach { it.onResult(false, null, "user cancelled") }
                }

                override fun onError(error: FacebookException?) {
                    error?.printStackTrace()
                    listeners.forEach { it.onResult(false, null, error?.message) }
                }

            })
    }

    fun logout() {
        require(isMainThread())
        //do nothing
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        callbackManager.onActivityResult(requestCode, resultCode, data)
    }
}